from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from .models import TranslateToHex
from .serializers import TranslateToHexSerializer
from django.shortcuts import render

@api_view(['POST'])
def to_hex(request):
    """
    将输入的字符串转换为十六进制表示并保存记录
    POST 请求需要包含 JSON 数据: {"input_string": "要转换的字符串"}
    返回: {"hex_string": "转换后的十六进制字符串"}
    """
    print("request data = {0}".format(request.data))
    # 检查请求数据是否为 JSON 格式
    if not request.data:
        return Response(
            {'error': '请提供 JSON 格式的输入数据'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # 获取输入字符串
    input_string = request.data.get('input_string', None)

    if input_string is None:
        return Response(
            {'error': '请提供 input_string 字段'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not isinstance(input_string, str):
        return Response(
            {'error': 'input_string 必须是字符串类型'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # 将字符串转换为十六进制表示
    try:
        # hex_string = input_string.encode('utf-8').hex()
        hex_string = ''.join(format(ord(c), '02x') for c in input_string)
        result_string = ' '.join('0x' + hex_string[i:i+2] for i in range(0, len(hex_string), 2))

        # 保存转换记录到数据库
        TranslateToHex.objects.create(
            original_string=input_string,
            hex_string=result_string
        )

        return Response({'hex_string': result_string})
    except Exception as e:
        return Response(
            {'error': f'转换失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )

@api_view(['POST'])
def hex_translate(request):
    """
    将输入的字符串转换为十六进制表示并保存记录
    POST 请求需要包含 JSON 数据: {"input_string": "要转换的字符串"}
    返回: {"hex_string": "转换后的十六进制字符串"}
    """
    # 检查请求数据是否为 JSON 格式
    if not request.data:
        return Response(
            {'error': '请提供 JSON 格式的输入数据'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # 获取输入字符串
    input_string = request.data.get('hex_string', None)

    if input_string is None:
        return Response(
            {'error': '请提供 input_string 字段'},
            status=status.HTTP_400_BAD_REQUEST
        )

    if not isinstance(input_string, str):
        return Response(
            {'error': 'input_string 必须是字符串类型'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # 将字符串转换为十六进制表示
    try:
        hex_str = input_string.replace(" ", "").replace("0x", "").replace("\n", "")
        result_string = bytes.fromhex(hex_str).decode('utf-8')
        print(result_string)
        TranslateToHex.objects.create(
            original_string=input_string,
            hex_string=result_string
        )
        return Response({'translated_string': result_string})
    except Exception as e:
        return Response(
            {'error': f'转换失败: {str(e)}'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )





class TranslateToHexViewSet(viewsets.ModelViewSet):
    queryset = TranslateToHex.objects.all()
    serializer_class = TranslateToHexSerializer

    def hex_converter_page(self, request):
        """显示字符串转十六进制工具页面"""
        return render(request, 'hex_converter.html')

    def blog_persion(self, request):
        """显示字符串转十六进制工具页面"""
        return render(request, 'blog_persion.html')


